﻿import mx.utils.Delegate;

/**
 * ...
 * @author Georg Kamptner
 */
class at.geoathome.utils.logging.sos.as2.log
{
	// -- fields ----------------------------------------
	private static var _xmlSocket:XMLSocket = new XMLSocket();
	private static var _connected:Boolean = false;
	private static var _cmdQueue:Array = new Array();
	
	public static var DEBUG:Number = 0;
	public static var INFO:Number = 1;
	public static var WARNING:Number = 2;
	public static var ALERT:Number = 3;
	public static var ERROR:Number = 4;
	
	// -- constructor -----------------------------------
	public function log()
	{
		throw new Error("'geo.sos.as2.log' is a static class no instances allowed, use log.*!");
	}
	
	// -- methods ---------------------------------------
	public static function c(host:String, port:Number):Boolean
	{
		if(host == undefined) host  = 'localhost'
		if(port == undefined) port = 4444;
		
		return log.connect(host, port);
	}
	
	public static function connect(host:String, port:Number):Boolean
	{
		if(host == undefined) host  = 'localhost'
		if(port == undefined) port = 4444;
		
		if(host == "") return false;
		if(port < 0) return false;
		
		// if connected close connection
		if(log._connected) log._xmlSocket.close();
		
		// start connection
		log._xmlSocket.connect(host, port);
		log._xmlSocket.onConnect = Delegate.create(log, onConnect);
		return true;
	}
	
	public static function onConnect():Void
	{
		log._connected = true;
		log._xmlSocket.send("!SOS<show/>");
		log._xmlSocket.send("!SOS<clear/>");
		log._xmlSocket.send("!SOS<setKey><name>0</name><color>"+0xffffff+"</color></setKey>");
		log._xmlSocket.send("!SOS<setKey><name>1</name><color>"+0xe1ffc6+"</color></setKey>");
		log._xmlSocket.send("!SOS<setKey><name>2</name><color>"+0xf9ffcf+"</color></setKey>");
		log._xmlSocket.send("!SOS<setKey><name>3</name><color>"+0xffe5c6+"</color></setKey>");
		log._xmlSocket.send("!SOS<setKey><name>4</name><color>"+0xffc6c6+"</color></setKey>");
		// execute all commands that were cast before the connection has been established.
		var l:Number = _cmdQueue.length;
		for(var i:Number=0; i<l; ++i)
		{
			log._xmlSocket.send(_cmdQueue[i]);
		}
	}
	
	public static function s(msg, type:Number):Void
	{
		if(msg == undefined) return;
		if(type == undefined) type = log.INFO;
		log.send(String(msg), type);
	}
	
	public static function send(msg, type:Number):Void
	{
		if(msg == undefined) return;
		if(type == undefined) type = log.INFO;
		
		// if not connected -> auto connect
		if(!log._connected) log.connect();
		
		// send msg
		var cmd:String = "!SOS<showMessage key='" + type + "'><![CDATA[" + String(msg) + "]]></showMessage>" +  String.fromCharCode(0);
		if(!_connected)
		{
			_cmdQueue.push(cmd);
		}
		else
		{
			var l:Number = _cmdQueue.length;
			for(var i:Number=0; i<l; ++i)
			{
				log._xmlSocket.send(_cmdQueue[i]);
			}
		}
	}
}